/* -*- mode: c++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- */

#ifndef _FILEUPDATENOTIFIER_H_
#define _FILEUPDATENOTIFIER_H_

#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include <string>

class FileUpdateNotifier {
public:
    std::string                         _file_name;

    time_t                              _last_modified_time;

    time_t                              _last_check_time;

    FileUpdateNotifier()
        : _last_modified_time(0)
        , _last_check_time(0)
    {
    }

    FileUpdateNotifier(const char *fn)
        : _file_name(fn)
        , _last_modified_time(0)
        , _last_check_time(0)
    {
        struct stat sb;

        if (stat(fn, &sb) == 0) {
            _last_check_time = time(NULL);
            _last_modified_time = sb.st_mtime;
        }
    }

    template<typename CB>
    bool update_check(CB cb, int check_freq)
    {
        bool check;

        if (check_freq > 0) {
            time_t now = time(NULL);

            if (now - _last_check_time >= check_freq)
                check = true;
            else
                check = false;
        }
        else
            check = true;

        if (!check)
            return false;

        struct stat sb;
        if (stat(_file_name.c_str(), &sb) == 0) {
            _last_check_time = time(NULL);

            if (_last_modified_time != sb.st_mtime) {
                _last_modified_time = sb.st_mtime;

                cb(_file_name.c_str());

                return true;
            }
        }

        return false;
    }
};

#endif /* _FILEUPDATENOTIFIER_H_ */
